package com.ll.config;

import javax.sql.DataSource;

import org.apache.ibatis.session.SqlSessionFactory;
import org.mybatis.spring.annotation.MapperScan;
import org.springframework.boot.bind.RelaxedPropertyResolver;
import org.springframework.context.EnvironmentAware;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.env.Environment;
import org.springframework.core.io.support.PathMatchingResourcePatternResolver;
import org.springframework.jdbc.datasource.DataSourceTransactionManager;
import org.springframework.transaction.PlatformTransactionManager;

import com.alibaba.druid.pool.DruidDataSource;
/**
 * 数据库相关的配置，包括数据源、事务�?�sessionFactory�?
 * @author sunhuaili
 *
 */
@Configuration
@MapperScan(basePackages="com.ll.dao.mapper", sqlSessionFactoryRef = "sqlSessionFactory")
public class DatabaseConfiguration implements EnvironmentAware {
	
	private RelaxedPropertyResolver propertyResolver;  
	
	@Bean
	public DataSource dataSource() {
		DruidDataSource datasource = new DruidDataSource();
		datasource.setUrl(propertyResolver.getProperty("url"));  
        datasource.setDriverClassName(propertyResolver.getProperty("driverClassName"));  
        datasource.setUsername(propertyResolver.getProperty("username"));  
        datasource.setPassword(propertyResolver.getProperty("password"));
		return  datasource;
	}
	
	@Bean
	public SqlSessionFactory sqlSessionFactory() throws Exception{
		org.mybatis.spring.SqlSessionFactoryBean sqlSessionFactoryBean = new org.mybatis.spring.SqlSessionFactoryBean();
		sqlSessionFactoryBean.setDataSource(dataSource());
		sqlSessionFactoryBean.setTypeAliasesPackage("com.ll.dao.entity");
		PathMatchingResourcePatternResolver resolver = new PathMatchingResourcePatternResolver();
		sqlSessionFactoryBean.setMapperLocations(resolver.getResources("classpath:com/ll/dao/mapper/*.xml"));
		SqlSessionFactory sqlSessionFactory = sqlSessionFactoryBean.getObject();
		org.apache.ibatis.session.Configuration configuration = sqlSessionFactory.getConfiguration();
		//添加分页的插件，MyBatis默认为�?�辑分页，添加这个插件之后，可以使用RowBounds实现物理分页
		//由于不同的数据库，分页方式不�?样，因此有个方言的设�?
		//该插件目前支持的方言为oracle,mysql,mariadb,sqlite,hsqldb,postgresql,db2,sqlserver,informix
		
		/*
		采用代码自动生成分页语句，不在利用插件进行分�?
		PageHelper pageHelper = new PageHelper();
		Properties prop = new Properties();
		prop.setProperty("dialect", "mysql");
		pageHelper.setProperties(prop);
		configuration.addInterceptor(pageHelper);
		*/
		return sqlSessionFactory;
	}
	
	@Bean
	public PlatformTransactionManager transactionManager() {
		return new DataSourceTransactionManager(dataSource());
	}

	@Override
	public void setEnvironment(Environment environment) {
		this.propertyResolver = new RelaxedPropertyResolver(environment, "spring.datasource.");  
	}
	
}
